#pragma once

#include "../source/tcp_server.hpp"
#include "../source/Log.hpp"
#include <fstream>
#include <sys/stat.h>
#include <regex>

std::unordered_map<int, std::string> _statu_msg = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

// 工具类
class Util
{
public:
    //字符串切割
    static int Split(const std::string &src, const std::string &sep, std::vector<std::string> *des)
    {
        size_t offset = 0;
        while (offset < src.size())
        {
            size_t pos = src.find(sep, offset);
            if (pos == std::string::npos)
            {
                des->push_back(src.substr(offset));
                break;
            }

            if (offset == pos)
            {
                offset = pos + sep.size();
                continue;
            }

            // 11.22
            des->push_back(src.substr(offset, pos - offset));
            offset = pos + sep.size();
        }

        return des->size();
    }


    //读文件
    static bool ReadFile(const std::string &filename, std::string *out)
    {
        std::ifstream ifs(filename, std::ios::binary);

        if (ifs.is_open() == false)
        {
            LOG(LogLevel::ERROR) << "打开文件 : " << filename << "失败";
            return false;
        }

        size_t file_size = 0;
        ifs.seekg(0, ifs.end);
        file_size = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        out->resize(file_size);

        ifs.read(&((*out)[0]), file_size);
        if (ifs.good() == false)
        {
            LOG(LogLevel::ERROR) << "文件 : " << filename << "  读取失败";
            ifs.close();
            return false;
        }

        LOG(LogLevel::INFO) << "文件 : " << filename << "  读取完成";
        ifs.close();
        return true;
    }


    //写文件
    static bool WriteFile(const std::string &filename, const std::string &in)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (ofs.is_open() == false)
        {
            LOG(LogLevel::ERROR) << "打开文件 : " << filename << "失败";
            return false;
        }

        ofs.write(in.c_str(), in.size());
        if (ofs.good() == false)
        {
            LOG(LogLevel::ERROR) << "文件 : " << filename << "  写入失败";
            ofs.close();
            return false;
        }

        ofs.close();
        LOG(LogLevel::INFO) << "文件 : " << filename << "  写入完成";
        return true;
    }

    // 1.  . - _ ~ 字母不需要转
    // 2.  ' ' -> '+' 看space_to_plus
    // 3.  其他转成%HH格式
    static std::string UrlEncode(const std::string url, bool space_to_plus)
    {
        std::string res;
        for (auto &e : url)
        {
            if (e == '.' || e == '-' || e == '_' || e == '~' || isalnum(e))
            {
                res += e;
                continue;
                ;
            }

            if (e == ' ' && space_to_plus)
            {
                res += '+';
                continue;
            }

            char tmp[4] = {0};
            snprintf(tmp, 4, "%%%02X", e);
            res += tmp;
        }

        return res;
    }

    static char HexToChar(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c - '0';
        }
        else if (c >= 'a' && c <= 'z')
        {
            return c - 'a' + 10;
        }
        else if (c >= 'A' && c <= 'Z')
        {
            return c - 'A' + 10;
        }

        return -1;
    }

    //解码
    static std::string UrlDecode(const std::string url, bool plus_to_space)
    {
        std::string res;
        for (int i = 0; i < url.size(); ++i)
        {
            if (url[i] == '+' && plus_to_space)
            {
                res += ' ';
                continue;
            }
            if (url[i] == '%' && (i + 2) < url.size())
            {
                char c1 = HexToChar(url[i + 1]);
                char c2 = HexToChar(url[i + 2]);
                res += ((c1 << 4) + c2);
                i += 2;
            }
            else
            {
                res += url[i];
            }
        }

        return res;
    }

    //获取状态码对应的状态描述
    static std::string StatusDesc(int code)
    {
        auto it = _statu_msg.find(code);
        if (it != _statu_msg.end())
        {
            return it->second;
        }

        return "UnKnow";
    }


    //根据文件格式获取对应的描述
    static std::string ExtMime(const std::string &namefile)
    {
        // 1.获取文件扩展名
        auto pos = namefile.find_last_of(".");
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }

        // 2.获得对应的名称
        auto it = _mime_msg.find(namefile.substr(pos));
        if (it == _mime_msg.end())
        {
            return "application/octet-stream";
        }

        return it->second;
    }


    //是否是正常的目录
    static bool IsDirector(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }

        return S_ISDIR(st.st_mode);
    }

    //是否是普通文件
    static bool IsRegular(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }

        return S_ISREG(st.st_mode);
    }


    //是否是正常的路径
    static bool VlaidPath(const std::string &path)
    {
        std::vector<std::string> res;
        Split(path, "/", &res);
        int level = 0;
        for (auto &s : res)
        {
            if (s == "..")
            {
                --level;
                if (level < 0)
                    return false;
                continue;
            }

            ++level;
        }

        return true;
    }
};


//请求
class HttpRequest
{
public:
    //设置头部字段
    void SetHeader(const std::string &key, const std::string &header)
    {
        _headers.insert(std::make_pair(key, header));
    }

    //是否存在该字段
    bool HasHerader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }

    //获取头部字段
    std::string GetHerder(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }

        return it->second;
    }


    //设置查找字符串
    void SetParmas(const std::string &key, const std::string &header)
    {
        _parmas.insert(std::make_pair(key, header));
    }


    //是否存在该查找字符串
    bool HasParmas(const std::string &key)
    {
        auto it = _parmas.find(key);
        if (it == _parmas.end())
        {
            return false;
        }
        return true;
    }

    //获取查找字符串
    std::string GetParmas(const std::string &key)
    {
        auto it = _parmas.find(key);
        if (it == _parmas.end())
        {
            return "";
        }

        return it->second;
    }

    //获取正文长度
    size_t ContentLength()
    {
        bool ret = HasHerader("Content-Length");
        if (ret == false)
        {
            return 0;
        }

        return std::stol(GetHerder("Content-Length"));
    }


    //是否是短连接
    bool Close()
    {
        if (HasHerader("Connection") == true && GetHerder("Connection") == "keep-alive")
        {
            return false;
        }
        return true;
    }

    //重置请求
    void Reset()
    {
        _method.clear();
        _path.clear();
        _version.clear();
        _body.clear();
        std::smatch smatch;
        _smatch.swap(smatch);
        _headers.clear();
        _parmas.clear();
    }

    void Print()
    {
        std::cout << "_method : " << _method << std::endl;
        std::cout << "_path : " << _path << std::endl;
        std::cout << "_version : " << _version << std::endl;
        std::cout << "_body : " << _body << std::endl;

        for (auto &e : _parmas)
        {
            std::cout << "_parmas_first : " << e.first << std::endl;
            std::cout << "_parmas_second : " << e.second << std::endl;
        }

        for (auto &e : _headers)
        {
            std::cout << "_headers_first : " << e.first << std::endl;
            std::cout << "_headers_second : " << e.second << std::endl;
        }
    }

public:
    std::string _method;  // 请求方法
    std::string _path;    // 请求资源路径
    std::string _version; // Http版本
    std::string _body;    // 正文内容
    std::smatch _smatch;  // 储存分割的内容

    std::unordered_map<std::string, std::string> _headers;  // 头部数据
    std::unordered_map<std::string, std::string> _parmas;   //查找字符串
};

class HttpResponse
{
public:
    HttpResponse()
        : _status(200),
          _is_redirect(false)
    {
    }

    HttpResponse(int status)
        : _status(status),
          _is_redirect(false)
    {
    }

    //重置响应
    void Reset()
    {
        _status = 200;
        _is_redirect = false;
        _redirect_url.clear();
        _body.clear();
        _headers.clear();
    }

    void SetHeader(const std::string &key, const std::string &header)
    {
        _headers.insert(std::make_pair(key, header));
    }

    bool HasHerader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }

    std::string GetHerder(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }

        return it->second;
    }


    //设置正文
    void SetBody(const std::string &body, const std::string &type = "text/plain")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }

    void SetRedirect(const std::string &redirect_url, int status = 302)
    {
        _status = true;
        _redirect_url = redirect_url;
        _status = status;
    }

    bool Close()
    {
        if (HasHerader("Connection") == true && GetHerder("Connection") == "keep-alive")
        {
            return false;
        }
        return true;
    }

    void Print()
    {
    }

public:
    int _status;                                           // 状态码
    bool _is_redirect;                                     // 是否重定向
    std::string _redirect_url;                             // 重定向的url
    std::string _body;                                     // 正文内容
    std::unordered_map<std::string, std::string> _headers; // 头部数据
};

typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatus;


//请求上下文类
const int MAX_LINE = 8096;
class HttpContext
{
public:
    HttpContext()
        : _rsp_status(200),
          _recv_status(HttpRecvStatus::RECV_HTTP_LINE)
    {
    }

    // 重置
    void Reset()
    {
        _rsp_status = 200;
        _recv_status = HttpRecvStatus::RECV_HTTP_LINE;
        _http_req.Reset();
    }

    // 返回响应状态码
    int GetRspStatus()
    {
        return _rsp_status;
    }

    // 返回处理数据的状态
    HttpRecvStatus GetRecvStatus()
    {
        return _recv_status;
    }

    // 返回处理好的请求
    HttpRequest GetHttpReq()
    {
        return _http_req;
    }

    // 处理数据
    void RecvHttpRequest(Buffer *buf)
    {
        switch (_recv_status)
        {
        case HttpRecvStatus::RECV_HTTP_LINE:
            RecvHttpLine(buf);
        case HttpRecvStatus::RECV_HTTP_HEAD:
            RecvHttpHead(buf);
        case HttpRecvStatus::RECV_HTTP_BODY:
            RecvHttpBody(buf);
        };
    }

private:
    // 处理第一行数据
    bool ParseHttpLine(const std::string &line)
    {
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, matches, e);
        if(ret == false)
        {
            _rsp_status = 400;
            _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
            return false;
        }

        // GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1
        // GET
        // /bitejiuyeke/login
        // user=xiaoming&pass=123123
        // HTTP/1.1

        // 提取请求方法
        _http_req._method = matches[1];
        std::transform(_http_req._method.begin(), _http_req._method.end(), _http_req._method.begin(), ::toupper);

        // 提取资源路径
        _http_req._path = Util::UrlDecode(matches[2], false);

        // 提取查找字符串
        std::vector<std::string> v;
        Util::Split(matches[3], "&", &v);
        for (auto &s : v)
        {
            size_t pos = s.find("=");
            if (pos == std::string::npos)
            {
                _rsp_status = 400;
                _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
                return false;
            }
            std::string key = Util::UrlDecode(s.substr(0, pos), true);
            std::string val = Util::UrlDecode(s.substr(pos + 1), true);

            _http_req.SetParmas(key, val);
        }

        // 提取协议版本
        _http_req._version = matches[4];

        return true;
    }

    bool RecvHttpLine(Buffer *buf)
    {
        if (_recv_status != HttpRecvStatus::RECV_HTTP_LINE)
        {
            return false;
        }

        std::string line = buf->GetLinePop();
        if (line.size() == 0)
        {
            if (line.size() > MAX_LINE)
            {
                _rsp_status = 414;
                _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
                return false;
            }

            return true;
        }

        if (line.size() > MAX_LINE)
        {
            _rsp_status = 414;
            _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
            return false;
        }

        bool ret = ParseHttpLine(line);
        if (ret == false)
        {
            _rsp_status = 414;
            _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
            return false;
        }

        _recv_status = HttpRecvStatus::RECV_HTTP_HEAD;
        return true;
    }

    // 处理头部
    bool ParseHttpHead(std::string &line)
    {
        if (line.back() == '\n')
        {
            line.pop_back();
        }
        if (line.back() == '\r')
        {
            line.pop_back();
        }

        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _rsp_status = 400;
            _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
            return false;
        }

        _http_req.SetHeader(line.substr(0, pos), line.substr(pos + 2));
        return true;
    }

    bool RecvHttpHead(Buffer *buf)
    {
        if (_recv_status != HttpRecvStatus::RECV_HTTP_HEAD)
        {
            return false;
        }

        while (1)
        {
            std::string line = buf->GetLinePop();
            if (line.size() == 0)
            {
                if (line.size() > MAX_LINE)
                {
                    _rsp_status = 414;
                    _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
                    return false;
                }

                return true;
            }

            if (line.size() > MAX_LINE)
            {
                _rsp_status = 414;
                _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
                return false;
            }

            if (line == "\r\n" || line == "\n")
            {
                break;
            }

            bool ret = ParseHttpHead(line);
            if (ret == false)
            {
                _rsp_status = 414;
                _recv_status = HttpRecvStatus::RECV_HTTP_ERROR;
                return false;
            }
        }

        _recv_status = HttpRecvStatus::RECV_HTTP_BODY;
        return true;
    }

    // 处理正文内容
    bool RecvHttpBody(Buffer *buf)
    {
        if (_recv_status != HttpRecvStatus::RECV_HTTP_BODY)
        {
            return false;
        }

        // 获取正文长度
        int content_length = _http_req.ContentLength();
        if (content_length == 0)
        {
            _recv_status = HttpRecvStatus::RECV_HTTP_OVER;
            return true;
        }

        int reality_length = content_length - _http_req._body.size();
        if (buf->ReadSize() >= reality_length)
        {
            _http_req._body.append(buf->ReadPtr(), reality_length);
            buf->ReadIndexSkewing(reality_length);
            _recv_status = HttpRecvStatus::RECV_HTTP_OVER;
            return true;
        }

        _http_req._body.append(buf->ReadPtr(), buf->ReadSize());
        buf->ReadIndexSkewing(buf->ReadSize());

        return true;
    }

private:
    int _rsp_status;             // 响应状态码
    HttpRecvStatus _recv_status; // 处理请求数据的状态
    HttpRequest _http_req;       // 请求
};

const int TIME_DEFAULT = 10;
using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
using Handlers = std::vector<std::pair<std::regex, Handler>>;

class HttpServer
{
public:
    HttpServer(uint16_t port, int timeout = TIME_DEFAULT)
    :_server(port)
    {
        _server.OpenTimeout(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected,this,std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage,this,std::placeholders::_1,std::placeholders::_2));
    }

    //设置相关函数
    void SetGetHandler(const std::string &name, Handler handler)
    {
        _get_route.push_back(std::make_pair(std::regex(name),handler));
    }
    void SetPostHandler(const std::string &name, Handler handler)
    {
        _post_route.push_back(std::make_pair(std::regex(name),handler));
    }
    void SetPutHandler(const std::string &name, Handler handler)
    {
        _put_route.push_back(std::make_pair(std::regex(name),handler));
    }
    void SetDeleteHandler(const std::string &name, Handler handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(name),handler));
    }

    //设置根目录
    void SetBaseDir(const std::string &base_dir)
    {
        bool ret = Util::IsDirector(base_dir);
        assert(ret == true);
        _base_dir = base_dir;
    }

    //设置线程个数
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }

    //开始
    void Listent()
    {
        _server.Start();
    }

private:
    // 错误处理
    void ErrorHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        // 1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp->_status);
        body += " ";
        body += Util::StatusDesc(rsp->_status);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        // 2. 将页面数据，当作响应正文，放入rsp中
        rsp->SetBody(body, "text/html");
    }

    // 构建响应、发送响应
    void WriteReponse(const ConnectionPtr &conn,  HttpRequest &req, HttpResponse &rsp)
    {
        //1. 先完善头部字段
        if (req.Close() == true) {
            rsp.SetHeader("Connection", "close");
        }else {
            rsp.SetHeader("Connection", "keep-alive");
        }
        if (rsp._body.empty() == false && rsp.HasHerader("Content-Length") == false) {
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if (rsp._body.empty() == false && rsp.HasHerader("Content-Type") == false) {
            rsp.SetHeader("Content-Type", "application/octet-stream");
        }
        if (rsp._is_redirect == true) {
            rsp.SetHeader("Location", rsp._redirect_url);
        }
        //2. 将rsp中的要素，按照http协议格式进行组织
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._status) << " " << Util::StatusDesc(rsp._status) << "\r\n";
        for (auto &head : rsp._headers) {
            rsp_str << head.first << ": " << head.second << "\r\n";
        }
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        //LOG(LogLevel::DEBUG) << rsp_str.str().c_str();
        //LOG(LogLevel::DEBUG) <<  rsp_str.str().size();
        //3. 发送数据
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }

    // 是否是静态资源
    bool IsFileHandler(const HttpRequest &req)
    {
        //1.必须是get 或 head 方法
        if(req._method != "GET" && req._method != "HEAD")
        {
            return false;
        }

        //2.是否是一个合法的路径
        if(Util::VlaidPath(req._path) == false)
        {
            return false;
        }

        //3.是否是一个合法文件
        std::string path = _base_dir + req._path;
        if(path.back() == '/')
        {
            path += "index.html";
        }

        if(Util::IsRegular(path) == false)
        {
            return false;
        }

        return true;
    }

    // 组织静态资源
    void FileHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        std::string path = _base_dir + req._path;
        if(path.back() == '/')
        {
            path += "index.html";
        }

        //1.读取文件
        std::string out;
        bool ret = Util::ReadFile(path,&out);
        if(ret == false)
        {
            return;
        }
        LOG(LogLevel::DEBUG) << out;
        //2.设置文件类型
        rsp->SetBody(out,Util::ExtMime(path));
    }

    // 组织动态资源
    void Dispatcher(HttpRequest &req, HttpResponse *rsp, Handlers &handlers)
    {
        for(auto &e : handlers)
        {
            bool ret = std::regex_match(req._path,req._smatch,e.first);
            if(ret == false)
            {
                continue;
            }

            e.second(req,rsp);
            return ;
        }

        rsp->_status = 404;
        ErrorHandler(req,rsp);
    }

    // 进行路由
    void Route(HttpRequest &req, HttpResponse *rsp)
    {
        //1.是否是一个静态资源请求
        if(IsFileHandler(req) == true)
        {
            LOG(LogLevel::DEBUG)<<"静态请求";
            FileHandler(req,rsp);
            return;
        }


        if(req._method == "GET" || req._method == "HEAD")
        {
            return Dispatcher(req,rsp,_get_route);
        }
        else if(req._method == "POST")
        {
            return Dispatcher(req,rsp,_post_route);
        }
        else if(req._method == "PUT")
        {
            return Dispatcher(req,rsp,_put_route);
        }
        else if(req._method == "DELETE")
        {
            return Dispatcher(req,rsp,_delete_route);
        }

        rsp->_status = 405;
    }

    // 建立连接
    void OnConnected(const ConnectionPtr &conn)
    {
        // 1.设置上下文
        conn->SetContext(HttpContext());
        LOG(LogLevel::INFO) << "完成建立连接";
    }

    // 触发可读
    void OnMessage(const ConnectionPtr &conn, Buffer *buffer)
    {
        while (1)
        {
            // 1.获取上下文数据
            HttpContext *context = conn->GetContext()->get<HttpContext>();
            // 2.处理buffer数据
            context->RecvHttpRequest(buffer);
            // 3.组织响应
            HttpRequest req = context->GetHttpReq();
            HttpResponse rsp(context->GetRspStatus());
            // 3.1出现错误
            if (context->GetRspStatus() >= 400)
            {
                ErrorHandler(req, &rsp);
                WriteReponse(conn, req, rsp);
                context->Reset();
                buffer->ReadIndexSkewing(buffer->ReadSize());
                conn->ShutDwon();
                return;
            }

            LOG(LogLevel::DEBUG)<<"req._body.size() : " <<req._body.size();

            // 3.2请求没完整
            if (context->GetRecvStatus() != HttpRecvStatus::RECV_HTTP_OVER)
            {
                //LOG(LogLevel::DEBUG) << "数据不完整";
                return;
            }

            // 3.3组织响应
            Route(req, &rsp);

            //3.4 发送响应
            WriteReponse(conn, req, rsp);

            //3.5 长短连接
            if(req.Close() == true)
            {
                //LOG(LogLevel::DEBUG)<<"req.Close()";
                conn->ShutDwon();
            }
          
            //3.6重置上下文
            context->Reset();
            LOG(LogLevel::DEBUG) << "完成重置";
        }
    }

private:
    Handlers _get_route;
    Handlers _put_route;
    Handlers _post_route;
    Handlers _delete_route;
    std::string _base_dir;
    TcpServer _server;
};
